<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\business\User as UserB;
use app\index\validate\User as UserV;

#[path('/index/controller', 'file path')]
#[class('Login', 'Login data handel')]
class Login extends Base
{
    public function initialize()
    {
        $this->config = config('common');

        $this->validate = new UserV();
        $this->business = new UserB();
    }

    public function index()
    {
        return view('', [
            'config' => $this->config,
        ]);
    }

    public function login()
    {
        #[('is post')]
        if (!$this->request->isPost()) {
            throw new \think\Exception("请求不合法");
        }

        $param = input('param.');

        if (!$this->validate->scene('login')->check($param)) {
            throw new \think\Exception($this->validate->getError());
        }

        // 根据 username 获取用户信息
        try {
            $user_data = $this->business->login($param['username'], $param['passwd']);
        } catch (\Exception $e) {
            return result(null, config('http.api_http_code.error'), $e->getMessage());
        }

        // 记录 session
        session(config("user.session"), $user_data);

        return result("/index", config('http.api_http_code.success'), '登陆成功');
    }

    #[function('logout', 'logout')]
    public function logout()
    {
        session(config('user.session'), null);
        return redirect('/index/login');
    }
}
